import os
import tempfile

from starlette.background import BackgroundTasks
from starlette.responses import FileResponse

from infirmary_admin_src.infirmary_common.infirmary_controller import IBaseController
from infirmary_admin_src.infirmary_common.infirmary_controller.rest_controller_with_depends import \
    RestControllerWithDepends
from fastapi import Request, Depends, Path, Body

from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.infirmary.businesses.schemas import SchemaBase
from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.infirmary.businesses.services.service_businesses import \
    Businesses

import pandas as pd
from fastapi import FastAPI, Response

class XParam(SchemaBase):
    '''
    账号密码登录参数
    '''
    pass
    appid:str= ''
    dc_number: str = ''
    si_name: str = ''
    si_number : str = ''
    stime:str = None
    etime:str = None
    ampm:str =None
    weekday:str =None
    statue:int = -1
    visit_user_name:str =None
    visit_user_phone :str =None



class IController(IBaseController):
    '''
    定制相关约束检测函数逻辑步序
    '''

    def __init__(self, *, request: Request,
                 schema_param: XParam = Depends(),
                 response: Response,
                 task: BackgroundTasks,
                 ):
        super().__init__(request=request)
        # 入参参数
        # 入参参数
        self.schema_param = schema_param
        # 使用自定义响应
        self.response_curr = True
        self.response = response
        self.task = task



@RestControllerWithDepends()
class InfirmaryBusinessesDoctorSchedulingOrderQuestDownloadListController(IController):

    def business_login(self):


        lists = Businesses.get_businesses_doctor_scheduling_order_query_list_download(
            appid=self.schema_param.appid,
            si_name=self.schema_param.si_name,
            si_number=self.schema_param.si_number,
            stime=self.schema_param.stime,
            etime=self.schema_param.etime,
            ampm=self.schema_param.ampm,
            statue=self.schema_param.statue,
            weekday=self.schema_param.weekday,
            visit_user_name=self.schema_param.visit_user_name,
            visit_user_phone=self.schema_param.visit_user_phone,
            dc_number=self.schema_param.dc_number, is_del_select_key=[], del_flag=0,
        )
        # print(lists)
        # 创建包含数据的 DataFrame（假设数据为 result_data）
        header = ["驻点医馆","所属就诊医生","预约就诊人姓名",'预约就诊人手机号码','预约就诊人性别','预约就诊人年龄',"预约就诊日期","预约就诊周几","预约上午或下午","预约时段","预约就诊时间明细",'预约下单时间','预约订单状态']


        stats = {1:'订单就绪,没支付',
                     2:'已支付成功',
                     3:'用户已取消订单',
                     4: '用户申请退款中',
                     5: '超时未支付状态',
                     6: '退款成功',
                     }
        def makd(v):
            newsa = {}

            sps = v.get('visit_time').split('-')
            newsa['si_name'] = v.get('si_name')
            newsa['visit_doctot_name'] = v.get('visit_doctot_name')
            newsa['visit_user_name'] = v.get('visit_user_name')
            newsa['visit_user_phone'] = v.get('visit_user_phone')
            newsa['visit_user_sex'] = v.get('visit_user_sex')
            newsa['visit_user_age'] = f"{v.get('visit_user_age')}岁"
            newsa['visit_day'] = v.get('visit_day')
            newsa['weed_day'] =sps[0]
            newsa['appm'] = sps[1]
            newsa['timesp'] = sps[2]
            newsa['visit_time'] = v.get('visit_time')
            newsa['ctime'] = v.get('ctime')
            newsa['statue'] = stats.get(v.get('statue'))
            return newsa

        if lists:
            result_data = [makd(v) for v in lists]



            df = pd.DataFrame(result_data)
            with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                temp_filename = temp_file.name
                df.to_csv(temp_filename, index=False,header=header)

            # 删除临时文件
            self.task.add_task(os.remove, temp_filename)
            # 返回查询内容
            return FileResponse(temp_filename, filename="export.csv", media_type="text/csv")
        else:
            return None
